package com.wangyadong.hobby.thread.lesson10withcocurrent;

import java.util.stream.IntStream;

public class RightLeftDeadLock {

    private final Object leftLock = new Object();
    private final Object rightLock = new Object();


    public void leftLock() {
        synchronized (leftLock) {
            synchronized (rightLock) {
                doSomething();
            }
        }
    }

    public void rightLock() {
        synchronized (rightLock) {
            synchronized (leftLock) {
                doSomethingElse();
            }
        }
    }
    void doSomething() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void doSomethingElse() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        RightLeftDeadLock leftDeadLock = new RightLeftDeadLock();
        IntStream.range(0,100).forEach(i->{
            new Thread(()->{
                leftDeadLock.leftLock();
            }).start();

            new Thread(()->{
                leftDeadLock.rightLock();
            }).start();
        });
    }

}
